package com.cswnode.Controller;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Entity.LoginTicket;
import com.cswnode.Entity.User;
import com.cswnode.Enums.ResponseEnum;
import com.cswnode.Service.LoginService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.Constant;
import com.cswnode.Util.RedisKeyUtil;
import com.cswnode.VO.ResponseVo;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    @Autowired
    public Producer kaptchaProduct;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;

    @Value("${server.servlet.context-path}")
    private String ContextPath;

    @GetMapping("/login")
    public String GoLoginPage(){
        return "/site/login";
    }

//    //生成验证码
//    @GetMapping("/kaptcha")
//    public void getkaptcha(HttpServletResponse response, HttpSession session){
//        //生成随机的字符串
//        String text = kaptchaProduct.createText();
//        //绘制字符串的验证码图片
//        BufferedImage image = kaptchaProduct.createImage(text);
//        //将验证码写入session
//        session.setAttribute("keptcha",text);
//        //将输入的图片输入到浏览器
//        response.setContentType("image/png");
//
//        try {
//            OutputStream outputStream = response.getOutputStream();
//            ImageIO.write(image,"png",outputStream);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    //生成验证码
    @GetMapping("/kaptcha")
    public void getkaptcha(HttpServletResponse response){
        //生成随机的字符串
        String text = kaptchaProduct.createText();
        //绘制字符串的验证码图片
        BufferedImage image = kaptchaProduct.createImage(text);
        //将验证码写入session
        //session.setAttribute("keptcha",text);

        //验证码归属
        String KaptchaOwner = CommunityUtil.getUUID();
        Cookie cookie = new Cookie("KaptchaOwner",KaptchaOwner);
        //设置cookie存在时间
        cookie.setMaxAge(60);
        //设置cookie生效路劲
        cookie.setPath(ContextPath);
        //添加cookie
        response.addCookie(cookie);
        //将验证码存入redis
        String redisKey = RedisKeyUtil.getKaptcha(KaptchaOwner);
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);


        //将输入的图片输入到浏览器
        response.setContentType("image/png");

        try {
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



//    @PostMapping("/login")
//    public String Login(String username, String password, String code, boolean rememberMe,
//                        Model model, HttpServletResponse response, HttpSession session){
//        System.out.println(rememberMe);
////        if (rememberMe == null){
////            rememberMe = false;
////        }
//        String keptcha = (String) session.getAttribute("keptcha");
//        if (StringUtils.isBlank(code) || StringUtils.isBlank(keptcha) || !keptcha.equalsIgnoreCase(code)){
//            model.addAttribute("codeMsg","验证码不正确");
//            return "/site/login";
//        }
//        System.out.println(rememberMe);
//        int ticketSecond = rememberMe ? Constant.REMEMBERME_TICKET_SECONDS : Constant.DEFAULT_TICKET_SECONDS;
//        Map<String, Object> login = loginService.Login(username, password, ticketSecond);
//        //判断map是否包含凭证
//        if (login.containsKey("ticket")){
//            Cookie cookie = new Cookie("ticket",login.get("ticket").toString());
//            cookie.setPath(ContextPath);
//            cookie.setMaxAge(ticketSecond);
//            response.addCookie(cookie);
//            return "redirect:/";
//        }else {
//            model.addAttribute("usernameMsg",login.get("usernameMsg"));
//            model.addAttribute("passwordMsg",login.get("passwordMsg"));
//            return "/site/login";
//        }
//    }

    @PostMapping("/login")
    public String Login(String username, String password, String code, boolean rememberMe,
                        Model model, HttpServletResponse response,@CookieValue("KaptchaOwner") String kaptchaOwner){
        //System.out.println(rememberMe);
//        if (rememberMe == null){
//            rememberMe = false;
//        }
        //String keptcha = (String) session.getAttribute("keptcha");


        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)){
            String redisKey = RedisKeyUtil.getKaptcha(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }

        if (StringUtils.isBlank(code) || StringUtils.isBlank(kaptcha) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "/site/login";
        }
        System.out.println(rememberMe);
        int ticketSecond = rememberMe ? Constant.REMEMBERME_TICKET_SECONDS : Constant.DEFAULT_TICKET_SECONDS;
        Map<String, Object> login = loginService.Login(username, password, ticketSecond);
        //判断map是否包含凭证
        if (login.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket",login.get("ticket").toString());
            cookie.setPath(ContextPath);
            cookie.setMaxAge(ticketSecond);
            response.addCookie(cookie);
            return "redirect:/";
        }else {
            model.addAttribute("usernameMsg",login.get("usernameMsg"));
            model.addAttribute("passwordMsg",login.get("passwordMsg"));
            return "/site/login";
        }
    }





    @LoginJudgment
    @GetMapping("/logout")
    public String logout(@CookieValue("ticket")String ticket){
        loginService.logout(ticket);
        return "redirect:/login";
    }

    @GetMapping("/lo")
    public ResponseVo<User> logout(){
        User user=new User();
        user.setPassword("21231");

        return ResponseVo.success(ResponseEnum.SUCCESS_LOGOUT);
    }
}
